package org.jeecg.modules.golf.question.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.golf.question.client.QuestionTypeAnalysisDTO;
import org.jeecg.modules.golf.question.client.qto.StatisticsQuestionAnalysisQueryDTO;
import org.jeecg.modules.golf.question.entity.QuestionType;
import org.jeecg.modules.golf.question.entity.QuestionTypeMapping;
import org.jeecg.modules.golf.question.mapper.QuestionTypeMappingMapper;
import org.jeecg.modules.golf.question.service.IQuestionTypeMappingService;
import org.jeecg.modules.golf.question.service.IQuestionTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 问题分类方案关联表
 * @Author: jeecg-boot
 * @Date:   2020-10-18
 * @Version: V1.0
 */
@Service
public class QuestionTypeMappingServiceImpl extends ServiceImpl<QuestionTypeMappingMapper, QuestionTypeMapping> implements IQuestionTypeMappingService {


	@Autowired
	private IQuestionTypeService questionTypeService;


	@Override
	public List<QuestionTypeMapping> selectByMainId(Long mainId) {
		return getBaseMapper().selectByMainId(mainId);
	}

	@Override
	public List<QuestionTypeMapping> selectByMappingIdList(List<Long> questionIdList, Integer mappingType) {
		return  getBaseMapper().selectByMappingIdList(questionIdList, mappingType);
	}



	/**
	 * 批量保存
	 * @param questionTypeMappingList
	 */
    @Override
    public void save(List<QuestionTypeMapping> questionTypeMappingList,Integer mappingType,Long mappingId) {
		if (questionTypeMappingList != null && questionTypeMappingList.size() > 0) {
			if(questionTypeMappingList.size()>5){
				throw  new JeecgBootException(mappingType ==1?"问题":"方案"+"最多关联5个问题分类");
			}
			for (QuestionTypeMapping entity : questionTypeMappingList) {
				//外键设置
				entity.setMappingType(mappingType);
				entity.setMappingId(mappingId);
				getBaseMapper().insert(entity);
			}

		}
	}


	/**
	 * 学员问题分类分布-统计

	 * @param statisticsQuestionAnalysisQueryDTO
	 * @return
	 */
	@Override
	public List<QuestionTypeAnalysisDTO> typeDistAnalysis(StatisticsQuestionAnalysisQueryDTO statisticsQuestionAnalysisQueryDTO) {
		List<QuestionTypeAnalysisDTO> questionTypeAnalysisDTOList = getBaseMapper().typeDistAnalysis(statisticsQuestionAnalysisQueryDTO);
		if(CollectionUtil.isEmpty(questionTypeAnalysisDTOList)){
			return questionTypeAnalysisDTOList;
		}
		//取出问题分类树结构
		//按节点深入分组 分组产品分类
		List<QuestionType> questionTypeList;
		questionTypeAnalysisDTOList.forEach(i->{
			List<String> questionTypeIdList = Arrays.asList(i.getTreePath().split(","));
			i.setQuestionTypeIdList(questionTypeIdList);
			i.setTraineeCount(i.getTraineeList().size());
			i.setDeep(questionTypeIdList.size());
		});
		//限定学员
		if(StringUtils.isNotBlank(statisticsQuestionAnalysisQueryDTO.getTraineeId())){
			Set<String> typeIdSet = questionTypeAnalysisDTOList.stream()
					.map(i -> i.getQuestionTypeIdList().stream())
					.flatMap(z -> z)
					.collect(Collectors.toSet());
			questionTypeList = questionTypeService.listByIds(typeIdSet);
		}else{
			questionTypeList = questionTypeService.list();
		}

		int maxDeep = questionTypeAnalysisDTOList.stream().mapToInt(QuestionTypeAnalysisDTO::getDeep).max().getAsInt() - 1 ;
		//List<QuestionTypeAnalysisDTO> analysisDTOList = questionTypeList.stream().map(i -> new QuestionTypeAnalysisDTO(i)).collect(Collectors.toList());
		Map<Integer, List<QuestionTypeAnalysisDTO>> deepQuestionTypeGroupMap = questionTypeAnalysisDTOList.stream().collect(Collectors.groupingBy(QuestionTypeAnalysisDTO::getDeep));
		//处理所有的问题分类统计对应的数量。

			List<QuestionTypeAnalysisDTO> child = deepQuestionTypeGroupMap.getOrDefault(maxDeep,new ArrayList<>());
			child.forEach(j->{
				int questionSum = questionTypeAnalysisDTOList.stream()
						.filter(z -> z.getParentId().equals(j.getQuestionTypeId()))
						.mapToInt(QuestionTypeAnalysisDTO::getQuestionCount).sum();
				Set<String> traineeIdList = questionTypeAnalysisDTOList.stream()
						.filter(z -> z.getParentId().equals(j.getQuestionTypeId()))
						.map(QuestionTypeAnalysisDTO::getTraineeList).flatMap(z -> z.stream()).collect(Collectors.toSet());
				j.setQuestionCount(Optional.ofNullable(j.getQuestionCount()).orElse(0)+ questionSum);
				j.getTraineeList().addAll(traineeIdList);
				j.setTraineeCount(traineeIdList.size());


			});
        maxDeep--;
        for( int i = maxDeep;i>=1 ;i--){
			child = deepQuestionTypeGroupMap.getOrDefault(i,new ArrayList<>());
			int finalI = i;
			child.forEach(j->{
				List<QuestionTypeAnalysisDTO> data = deepQuestionTypeGroupMap.get(finalI + 1);
				if(data == null){
					return ;
				}
				int questionSum = data.stream()
						.filter(z -> z.getParentId().equals(j.getQuestionTypeId()))
						.mapToInt(QuestionTypeAnalysisDTO::getQuestionCount).sum();
				Set<String> traineeIdList =  data.stream()
						.filter(z -> z.getParentId().equals(j.getQuestionTypeId()))
						.map(QuestionTypeAnalysisDTO::getTraineeList).flatMap(z -> z.stream()).collect(Collectors.toSet());
				j.setQuestionCount(Optional.ofNullable(j.getQuestionCount()).orElse(0)+ questionSum);
				j.setTraineeList(traineeIdList);
				j.setTraineeCount(traineeIdList.size());

			});
		}
		questionTypeAnalysisDTOList.clear();
		questionTypeAnalysisDTOList.addAll(deepQuestionTypeGroupMap.values().stream().flatMap(j -> j.stream()).collect(Collectors.toList()));
		//查找所有的分类。
		Map<String, QuestionType> questionTypeMap = questionTypeList.stream()
				.collect(Collectors.toMap(QuestionType::getId, Function.identity()));
		questionTypeAnalysisDTOList.stream().forEach(i->{
			StringBuilder questionTypeName = new StringBuilder();
			List<String> questionTypeIdList = i.getQuestionTypeIdList();
			for (int j = 0; j < questionTypeIdList.size(); j++) {
				questionTypeName.append(questionTypeMap.get(questionTypeIdList.get(j)).getName());
				if(j < questionTypeIdList.size()-1){
					questionTypeName.append("-");
				}
			}
			i.setTreePathStr(questionTypeName.toString());

		});
		return questionTypeAnalysisDTOList;



	}
}
